package com.bigboss.knowstar.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtil {

    private static final String SALT = "knowstar";

    public static String generateToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);

        return builder
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SALT));
    }

    public static DecodedJWT verify(String token) {
        // 验证成功则返回DecodedJWT
        // 验证失败则抛出相应的异常
        return JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
    }

}
